<template>
  <div class="app-container cliptask">
    <div class="header">
      <div class="title">
        <h3>{{ $route.meta.subTitle }}</h3>
      </div>
    </div>
    <div id="mainContainer" class="up s-border">
      <live-video-area-view
        v-if="video && video.sourceUrl"
        id="mainPlayer"
        ref="mainPlayer"
        :url="video.sourceUrl"
        style="width: 300px; height: 200px;display:none;"/>
    </div>
    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input v-model="listQuery.title" clearable class="filter-item" style="width: 200px;" placeholder="请输入名称"/>
      <el-button class="filter-item" icon="el-icon-search" @click="handleFilter">查找</el-button>
      <el-button class="filter-item" type="primary" icon="el-icon-edit" @click="handleCreate">添加</el-button>
      <!--      <el-button class="filter-item" icon="el-icon-download">下载所有</el-button>-->
    </div>
    <!-- 查询结果 -->
    <el-table v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。" border fit highlight-current-row>
      <el-table-column align="center" label="id" prop="id" width="60"/>
      <el-table-column align="center" label="封面">
        <template slot-scope="props">
          <span>
            <img :src="props.row.posterUrl" style="width:100px;height:100px;" alt="">
          </span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="素材名称" prop="title"/>

      <!-- <el-table-column align="center" label="一级分类" width="100">
        <template slot-scope="props">
          <div>
            <span>{{ props.row.cateOneText }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="二级分类" width="100">
        <template slot-scope="props">
          <div>
            <span>{{ props.row.cateTwoText }}</span>
          </div>
        </template>
      </el-table-column> -->
      <el-table-column align="center" label="来源">
        <template slot-scope="props">
          <div>
            <span>{{ props.row.sourceType|from }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="剪辑状态">
        <template slot-scope="props">
          <span v-show="props.row.status==0">剪辑中</span>
          <span v-show="props.row.status==1">已完成</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="下载状态">
        <template slot-scope="props">
          <span v-show="props.row.downStatus==0">下载中</span>
          <span v-show="props.row.downStatus==1">下载完成</span>
          <span v-show="props.row.downStatus==2">下载失败</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="创建时间" prop="addTime"/>

      <el-table-column align="center" label="操作" min-width="200">
        <template slot-scope="scope">
          <div style="">
            <el-dropdown class="btn" size="mini">
              <span class="el-dropdown-link">
                <el-button size="mini">更多</el-button>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item @click.native="handleDownload(scope.row)"> 全部下载 </el-dropdown-item>
                <!-- <el-dropdown-item @click.native="handleUpdate(scope.row)"> 修改 </el-dropdown-item> -->
                <el-dropdown-item @click.native="handleDelete(scope.row)"> 删除 </el-dropdown-item>
                <!-- <el-dropdown-item @click.native="handleStatus(scope.row)"> 设为{{ findInList(VideoStatusContants, 'key', getNewStatus(scope.row.status), 'value') }} </el-dropdown-item> -->
              </el-dropdown-menu>
            </el-dropdown>
            <el-button size="mini" @click="handleEdit(scope.row)">剪辑</el-button>
            <el-button size="mini" @click="todetail(scope.row)">查看详情</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <pagination :total="total" :page.sync="page" :limit.sync="listQuery.limit" @pagination="getList" />
    <!-- 新建剪辑任务弹窗 -->
    <el-dialog v-if="dialogFormVisible" :visible.sync="dialogFormVisible" title="添加剪辑素材" style="width: 100%;" close>
      <el-form ref="dataForm" :model="dataForm" status-icon label-position="right" label-width="120px" style="width: 90%; margin-left:20px;">
        <el-form-item>
          <el-button type="primary" size="mini" @click="selectSource">素材库选择</el-button>
          <el-button type="primary" size="mini" @click="videotype=1,dataForm.sourceUrl=''">m3u8链接视频</el-button>
          <el-button type="primary" size="mini" @click="videotype=2,dataForm.sourceUrl=''">本地上传视频</el-button>
        </el-form-item>
        <el-form-item prop="sourceUrl">
          <div v-show="videotype==1">
            <el-input v-model="dataForm.sourceUrl" type="textarea" placeholder="输入m3u8链接地址" @blur="getm3u8"/>
            <!-- <el-button type="primary" size="mini" @click="selectSource">素材库选择</el-button> -->
          </div>
          <div v-show="videotype==2">
            <file-uploader v-model="dataForm.sourceUrl" type="video" accept="video/mp4" @uploaded="onVideoLoaded" @beforeupload="beforeupload"/>
          </div>
        </el-form-item>
        <el-form-item v-show="Object.keys(videoinfo).length>0&&videotype==2">
          <div>
            <span>素材大小：{{ videoinfo.size }}</span>
            <span>素材时长：{{ videoinfo.time }}</span>
            <span>素材格式：{{ videoinfo.type }}</span>
          </div>
        </el-form-item>
        <el-form-item label="任务名称" prop="title">
          <el-input v-model="dataForm.title" type="textarea"/>
        </el-form-item>
        <el-form-item label="期数ID" prop="playId">
          <el-input v-model="dataForm.playId" type="textarea"/>
        </el-form-item>
        <!-- <el-form-item label="选择分类" prop="stationName">
          <span>
            <el-select v-model="fir_cate" class="select" placeholder="请选择一级分类">
              <el-option
                v-for="item in fir_options"
                :key="item.id"
                :label="item.name"
                :value="item.id"/>
            </el-select>
          </span>
          <span>
            <el-select v-model="sec_cate" class="select" placeholder="请选择二级分类">
              <el-option
                v-for="item in sec_options"
                :key="item.id"
                :label="item.name"
                :value="item.id"/>
            </el-select>
          </span>
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">关闭</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">确定</el-button>
        <el-button v-else type="primary" @click="updateData">确定</el-button>
      </div>
    </el-dialog>

    <!-- 媒资库选择弹窗 -->
    <el-dialog v-if="dialogFormVisible1" :visible.sync="dialogFormVisible" title="选择资源" style="width: 100%;" close>
      <div class="filter-container">
        <el-input v-model="sourceQuery.title" clearable class="filter-item" style="width: 200px;" placeholder="请输入名称"/>
        <el-button class="filter-item" icon="el-icon-search" @click="searchsource_list">查找</el-button>
      </div>
      <el-table
        v-loading="listLoading"
        :data="source_list"
        max-height="400"
        element-loading-text="正在查询中。。。"
        border
        fit
        highlight-current-row
        @current-change="handleSelectionChange"
      >
        <el-table-column align="center" label="素材名称" prop="title"/>
        <el-table-column align="center" label="一级分类" width="100">
          <template slot-scope="props">
            <div>
              <span>{{ props.row.cateOneText }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="二级分类" width="100">
          <template slot-scope="props">
            <div>
              <span>{{ props.row.cateTwoText }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column align="center" label="上传时间" prop="addTime"/>

      </el-table>
      <pagination :total="total1" :page.sync="page1" :limit.sync="sourceQuery.limit" style="padding:0;" @pagination="getsoureList" />
      <div slot="footer" class="dialog-footer" style="padding:0;margin:0;">
        <el-button @click="dialogFormVisible1 = false">取消</el-button>
        <!-- <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">确定</el-button> -->
        <el-button type="primary" @click="sureSelect">确定选择</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>

import BackToTop from '../../../components/BackToTop'
import Pagination from '../../../components/Pagination'
import ObjectUtil from '../../../utils/object-util'
import { apiVideo as API } from '../../../api/clip/task'
import FileUploader from '../../../components/common/FileUploader'
import Fn from '../../../utils/fn'
import { ClipVideoTypeContants, VideoStatusContants } from '../../../mixin/MixinContants'
import { apiMeterial } from '../../../api/mediaManage/index'
import { apiUpload } from '../../../api/upload'
import { FileUtil } from '../../../utils/file-util'
import Common from '../../../utils/common'

export default {
  name: 'APIList',
  components: {
    FileUploader,
    BackToTop,
    Pagination,
  },
  filters: {
    from(val) {
      if (val === 0) {
        return 'm3u8上传'
      } else if (val == 1) {
        return '本地上传'
      } else if (val == 2) {
        return '媒资库选择'
      }
    }
  },
  mixins: [
    ClipVideoTypeContants.mixin,
    VideoStatusContants.mixin
  ],
  data() {
    return {
      // present: 0,
      // // total:0,
      // allPage: 1,
      video: { sourceUrl: '' },
      page: 1,
      page1: 1,
      total: 0,
      total1: 0,
      videotype: '',
      list: [],
      source_list: [],
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 10,
        id: undefined,
        tag: undefined,
        title: undefined
      },
      sourceQuery: {
        page: 1,
        limit: 10,
        id: undefined,
        tag: undefined,
        title: undefined,
        type: 1
      },
      dataForm: {
        playId: '',
        sourceUrl: '',
        title: '',
        // cateOneList: [],
        // cateTwoList: [],
        posterUrl: undefined,
        sourceType: undefined,
        meterialType: '1'
      },
      dialogFormVisible: false,
      dialogFormVisible1: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      downloadLoading: false,
      fir_cate: '',
      sec_cate: '',
      // 二级分类下拉数据
      sec_options: [],
      // 一级分类下拉数据
      fir_options: [],
      // 视频信息
      videoinfo: {}
    }
  },
  created() {
    this.Init()
  },
  methods: {
    // 去剪辑详情
    todetail(row) {
      this.$router.push(`/clip/clipdetail?id=${row.id}`)
    },
    sureSelect() {
      this.video.sourceUrl = this.dataForm.sourceUrl
      this.dialogFormVisible1 = false
    },
    clipImage() {
      const canvas = document.createElement('canvas')
      const canvasCtx = canvas.getContext('2d')
      const video = document.getElementById('mainPlayer')
      console.log(video)
      video.currentTime = 5
      canvas.width = video.videoWidth
      canvas.height = video.videoHeight
      canvasCtx.drawImage(video, 0, 0, video.videoWidth, video.videoHeight)
      const dataUrl = canvas.toDataURL('image/png')
      return dataUrl
    },
    // base64转二进制流
    tofileobj(data) {
      const binary = atob(data.split(',')[1])
      const mime = data.split(',')[0].match(/:(.*?);/)[1]
      const array = []
      for (let i = 0; i < binary.length; i++) {
        array.push(binary.charCodeAt(i))
      }
      const fileData = new Blob([new Uint8Array(array)], {
        type: mime
      })

      const file = new File([fileData], `${new Date().getTime()}.png`, { type: mime })
      return file
    },
    // 上传
    uploaddata(data) {
      const form = new FormData()
      form.append('file', data)
      apiUpload.upload(form).then(res => {
        this.dataForm.posterUrl = res.data.datas.url
      }).catch()
    },
    // 从m3u8链接中获取封面
    getm3u8() {
      // alert(1)
      const that = this
      const index = this.dataForm.sourceUrl.lastIndexOf('.')
      const type = this.dataForm.sourceUrl.substring(index)
      const ism3u8 = type.trim(type)
      if (this.dataForm.sourceUrl == '') {
        return this.toast.fail('不能为空')
      } else if (ism3u8 != '.m3u8') {
        return this.toast.fail('不是m3u8的链接')
      }
      // this.getvideoinfo()
      this.video.sourceUrl = String.trim(this.dataForm.sourceUrl)
    },
    // 单选
    handleSelectionChange(val) {
      console.log(val)
      this.dataForm.sourceUrl = val.url
      this.dataForm.sourceType = val.id
    },
    // 显示媒资库选择弹窗
    selectSource() {
      this.dataForm.sourceUrl = ''
      this.videotype = ''
      this.dialogFormVisible1 = true
      this.getsoureList()
    },
    // 媒资库搜索
    searchsource_list() {
      this.page1 = 1
      this.getsoureList()
    },
    // 获取分类信息
    getCategory() {
      apiMeterial.categoryList().then(res => {
        const result = res.data.datas.list
        this.fir_options = result.filter(item => item.level === 1)
          .map(item => {
            return {
              id: item.id,
              level: item.level,
              name: item.name
            }
          })
        this.sec_options = result.filter(item => item.level === 2)
          .map(item => {
            return {
              id: item.id,
              level: item.level,
              name: item.name
            }
          })
      }).catch((err) => { console.log(err) })
    },
    getNewStatus(status) {
      return (status + 1) % 2
    },
    Init() {
      this.getList()
      this.getCategory()
    },
    // 列表搜索
    handleFilter() {
      this.page = 1
      this.getList()
    },
    // 页面列表的数据
    getList() {
      // const api = API.list
      this.listLoading = true
      this.listQuery.page = this.page
      API.list({ ...this.listQuery }).then(res => {
        if (res.data.resp_code == 0) {
          this.list = res.data.datas.list || []
          this.total = Number(res.data.datas.total)
        } else {
          this.toast.fail(res.data.resp_msg)
        }
        // this.list = resList.filter(t => ObjectUtil.notNull(t))
      }).finally(() => {
        this.listLoading = false
      })
    },
    // 弹框媒资库列表数据
    getsoureList() {
      // const api = API.list
      this.listLoading = true
      this.sourceQuery.page = this.page1
      apiMeterial.list({ ...this.sourceQuery }).then(res => {
        if (res.data.resp_code == 0) {
          this.source_list = res.data.datas.list || []
          // console.log(res.data)
          this.total1 = Number(res.data.datas.total)
        } else {
          this.toast.fail(res.data.resp_msg)
        }
        // this.list = resList.filter(t => ObjectUtil.notNull(t))
      }).finally(() => {
        this.listLoading = false
      })
    },
    beforeupload(data) {
      console.log(data, '22222222222')
      let c = ''
      const that = this
      const url = URL.createObjectURL(data)
      var audioElement = new Audio(url)
      audioElement.addEventListener('loadedmetadata', function() {
        const duration = parseInt((audioElement.duration)) // playTime就是当前视频长度
        const b = parseInt(duration) % 60
        if (duration > 60) {
          const a = parseInt(duration) / 60
          c = a + 'min' + b + 's'
        } else {
          c = b + 's'
        }
        that.$set(that.videoinfo, 'time', c)
        that.$set(that.videoinfo, 'size', (data.size / 1024 / 1024).toFixed(2) + 'MB')
        that.$set(that.videoinfo, 'type', data.type.split('/')[1])
      })
    },
    onVideoLoaded(data) {
      this.video.sourceUrl = data.url
    },
    resetForm() {
      this.dataForm = {
        playId: '',
        sourceUrl: '',
        title: '',
        // cateOneList: [],
        // cateTwoList: [],
        posterUrl: undefined,
        sourceType: undefined,
        meterialType: '1'
      }
      this.videoinfo = {}
    },
    handleCreate() {
      this.videotype = ''
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible1 = false
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      if (this.dataForm.sourceUrl == '') {
        return this.toast.fail('请选择一个视频')
      }
      if (this.dataForm.title == '') {
        return this.toast.fail('请填写名称')
      }
      const loading = this.$loading({
        lock: true,
        text: '请稍等',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      // setTimeout(() => {
      this.$nextTick(() => {
        const video = this.$refs.mainPlayer
        // video.currentTime(3)
        const poster = video.clipImage()
        // console.log(a, 'video')
        if (this.videotype) {
          this.dataForm.sourceType = this.videotype == 1 ? 0 : 1
        }
        // const fir = this.fir_options.filter(item => this.fir_cate == item.id)
        // const sec = this.sec_options.filter(item => this.sec_cate == item.id)
        // this.dataForm.cateOneList = fir
        // this.dataForm.cateTwoList = sec
        this.dataForm.sourceUrl = String.trim(this.dataForm.sourceUrl)
        const create = () => {
          API.create(this.dataForm)
            .then(response => {
              if (response.data.resp_code == 0) {
                this.getList()
                this.dialogFormVisible = false
                loading.close()
                this.$notify.success({
                  title: '成功',
                  message: '创建成功'
                })
              } else {
                loading.close()
                this.toast.fail(response.data.resp_msg)
              }
            })
            .catch(response => {
              loading.close()
              // alert(1)
              this.$notify.error({
                title: '失败',
                message: (response.data.resp_msg || {})['errmsg'] || '请联系系统管理员'
              })
            })
        }
        // posterUrl 是否为url地址
        if (poster.match(/^data\:image/g)) {
          FileUtil.base64ToBolb(Common._randomString(12) + '.png', poster).then(res => {
            FileUtil.updateLoadFile(res).then(res => {
              const data = res.data.datas
              if (ObjectUtil.notNull(data) && ObjectUtil.notNull(data.url)) {
                this.dataForm.posterUrl = data.url
                create()
              }
            })
          })
        } else {
          create()
        }
      // }, 1000)
      })
    },
    handleUpdate(row) {
      this.dataForm = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          API.update(this.dataForm)
            .then(() => {
              for (const v of this.list) {
                if (v.id === this.dataForm.id) {
                  const index = this.list.indexOf(v)
                  this.list.splice(index, 1, this.dataForm)
                  break
                }
              }
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '更新成功'
              })
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: (response.data.resp_msg || {})['errmsg'] || '请联系系统管理员'
              })
            })
        }
      })
    },
    handleStatus: Fn.Confirm(function(row) {
      API.status({ id: row.id, status: this.getNewStatus(row.status) })
        .then(response => {
          if (response.data.resp_code == 0) {
            this.$notify.success({
              title: '成功',
              message: '修改状态成功'
            })
            if (ObjectUtil.notNull(response.data.data)) {
              row.status = response.data.data.status || 0
            }
            this.getList()
          }
        })
        .catch(response => {
          this.$notify.error({
            title: '失败',
            message: (response.data.resp_msg || {})['errmsg'] || '请联系系统管理员'
          })
        })
    }),
    handleDelete: Fn.Confirm(function(row) {
      API.delete({ id: row.id })
        .then(response => {
          if (response.data.resp_code === 0) {
            this.getList()
            this.$notify.success({
              title: '成功',
              message: '删除成功'
            })
          } else {
            this.toast.fail(response.data.resp_msg)
          }
          // const index = this.list.indexOf(row)
          // this.list.splice(index, 1)
        })
        .catch(response => {
          this.$notify.error({
            title: '失败',
            message: (response.data.resp_msg || {})['errmsg'] || '请联系系统管理员'
          })
        })
    }),
    handleEdit(row) {
      if (row.downStatus == 1) {
        this.$router.push({ name: 'RadioMeterialClipEdit', query: { id: row.id, title: row.title }})
      } else {
        this.toast.fail('后台正在处理，稍后再试')
      }
    },
    handleDownload: Fn.Confirm(function(row) {
      const loading = this.$loading({
        lock: true,
        text: '下载中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      const finalName = (row.id || '0') + '_视频下载集合'
      API.cliplist_all({ taskId: row.id }).then(res => {
        const clipList = res.data.datas.list || []
        const pArr = []
        const fileDataList = []
        clipList.filter(clip => ObjectUtil.notEmpty(clip.meterialUrl)).forEach(clip => {
          fileDataList.push({ filename: clip.title + '.mp4', data: null })
          pArr.push(API.file(clip.meterialUrl)())
        })

        Promise.all(pArr).then(resList => {
          resList.forEach((data, index) => {
            console.log(data, index)
            fileDataList[index].data = data.data
          })
          FileUtil.fileBatchDownload(finalName, fileDataList).then(downRes => {
            this.$notify.success({
              title: '成功',
              message: '批量下载成功'
            })
          }).catch(response => {
            this.$notify.error({
              title: '失败',
              message: (response.data.resp_msg || {})['errmsg'] || '请联系系统管理员'
            })
          }).finally(() => {
            loading.close()
          })
        })
      })
    })
  }
}
</script>

<style lang='scss' scoped>
  .cliptask{
    .header{
        width: 100%;
        height:50px;
        overflow: hidden;
        // background: #F2F2F2;
        margin: 10px 0;
        display: flex;
        .title{
            height:50px;
            line-height: 50px;
            text-align: left;
            width:20%;
            h3{
              margin: 0;
              display: inline-block;
              margin-left: 10px;

            }
        }

    }
  }
</style>
